package com.tarena.lbs.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tarena.lbs.basic.dao.mapper.TagMapper;
import com.tarena.lbs.basic.pojo.po.TagLibraryPO;
import com.tarena.lbs.basic.pojo.vo.TagLibraryVO;
import com.tarena.lbs.basic.pojo.vo.TagVO;
import com.tarena.lbs.basic.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by Mikazuki on 2025/6/9.
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, TagLibraryPO> implements TagService {
    @Override
    public Map<String, List<TagVO>> getTagsByType(int tagType) {
        LambdaQueryWrapper<TagLibraryPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TagLibraryPO::getTagType, tagType);
        List<TagLibraryPO> pos = list(queryWrapper);
        return toMap(pos);
    }

    private Map<String, List<TagVO>> toMap(List<TagLibraryPO> pos) {
        Map<String, List<TagVO>> map = pos.stream().filter(po -> po.getTagParentId() == null || po.getTagParentId().equals(0))
                .collect(HashMap::new, (m, po) -> {
                    List<TagVO> vos = pos.stream().filter(p -> p.getTagParentId() != null && p.getTagParentId().equals(po.getId()))
                            .map(p -> {
                                TagVO vo = new TagVO();
                                vo.setTagCategoryName(po.getTagName());
                                TagLibraryVO bo = new TagLibraryVO();
                                BeanUtils.copyProperties(p, bo);
                                vo.setTagLibraryBO(bo);
                                return vo;
                            })
                            .collect(Collectors.toList());
                    m.put(po.getTagName(), vos);
                }, HashMap::putAll);
        return map;
    }
}
